<template>
	<view class="app app-bg">
		<!-- 页面内容开始 -->
		<view class="list-page">

			<!--头部开始 -->
			<view class="list-head">
				<view class="list-search">
					<view class="list-search-input">
						<!-- 快捷搜索 -->
						<u-search v-model="queryForm1.formData[listSearch.key]" :placeholder="listSearch.placeholder" :show-action="false" input-align="center" class="search-input" shape="square" @search="search" @clear="search"></u-search>
						<!-- 高级搜索按钮图标 -->
						<u-icon class="advanced-search" name="list-dot" color="#909399" size="40" @click="show.advancedSearch = true" ></u-icon>
					</view>
					<!-- 状态筛选 -->
					<view class="subsection">
						<u-subsection :list="subsection1.list" v-model="subsection1.current"
							active-color="#000000" bg-color="#eeeeef"  @change="sectionChange1"></u-subsection>
					</view>
				</view>
				<!-- 总记录数 -->
				<view class="total-desc"> 共 <text class="total-num">{{ data.total }}</text> 条记录 </view>
				<!-- <view v-if="options.mode == 'choose'" class="choose-tips">
					点击对应地址即可选择
				</view> -->
			</view>
			<!--头部结束 -->

			<!--无内容时 -->
			<view v-if="data.list.length == 0" style="padding: 40% 0 80% 0;">
				<u-empty v-if="loading" text="查询中..." mode="search"></u-empty>
				<u-empty v-else text="暂无内容" mode="list"></u-empty>
			</view>
			<!--有内容时开始-->
			<view v-else class="list-main">
				<block v-for="(item, index) in data.list" :key="item._id">
					<!-- ****************** 自定义item的内容开始 ****************** -->

					<view class="list-item">
						<view class="content" @click.stop="collapse(index, item)">
							<view class="info">
								<text class="name">{{ item.name }}</text>
								<text class="mobile">{{ item.mobile }}</text>
								<u-tag v-if="item.alias" :text="item.alias" bg-color="#000000" size="mini" mode="dark" shape="circle" class="tag" />
								<u-tag v-if="item.is_default" text="默认" bg-color="#000000" size="mini" mode="dark" shape="circle" class="tag" />
							</view>
							<view class="address">{{ item.formatted_address }}</view>
						</view>
						<view class="collapse" :class="footer.actived === index ? 'actived' : 'actived'">
							<block v-for="(btn, btnIndex) in footer.list" :key="btnIndex">
								<view v-if="footerShowFn(btn, item, index)" @click="footerBtn(item, index, btn)" :class="btn.main ? 'main':''">
									{{ btn.text }}
								</view>
							</block>
						</view>
					</view>

					<!-- ****************** 自定义item的内容结束 ****************** -->
				</block>
				<!-- 加载更多-->
				<u-loadmore :status="state.loadmore" bg-color="var(--bgcolor)" margin-bottom="30" @loadmore="nextPage" />
			</view>
			<!--有内容时结束-->
			<view class="list-footer">
				<view class="btn-box">
					<!-- #ifdef MP-WEIXIN -->
					<view class="btn-secondary" @click="pageToForm()">手动新增地址</view>
					<view class="btn-main" @click="importWeixin">导入微信地址</view>
					<!-- #endif -->
					<!-- #ifndef MP-WEIXIN -->
					<view class="btn-main btn-one" @click="pageToForm()">手动新增地址</view>
					<!-- #endif -->
				</view>
			</view>

		</view>


		<!-- 高级搜索弹窗开始 -->
		<u-popup v-model="show.advancedSearch" mode="top" closeable>
			<view class="search-popup">
				<scroll-view scroll-y="true" class="scroll-view">
					<view>
						<!-- ****************** 自定义高级搜索表单开始 ****************** -->
						<u-form
							:model="queryForm1.formData"
							ref="queryForm1"
							label-position="top"
							:label-style="{ fontWeight: '500' }"
						>
							<u-form-item label="添加时间" prop="_add_time">
								<view class="date-range" @click="show._add_time = true">
									{{ queryForm1.formData._add_time[0] ? $fn.timeFormat(queryForm1.formData._add_time[0], "yyyy/MM/dd") + " - " + $fn.timeFormat(queryForm1.formData._add_time[1], "yyyy/MM/dd") : "日期范围" }}
								</view>
							</u-form-item>
							<u-form-item label="姓名" prop="name">
								<u-input v-model="queryForm1.formData.name" />
							</u-form-item>
							<u-form-item label="手机号" prop="mobile">
								<u-input v-model="queryForm1.formData.mobile" />
							</u-form-item>
							<u-form-item label="标签" prop="alias">
								<view style="width: 100%;">
									<u-subsection :list="subsection1.list" v-model="subsection1.current"
										active-color="#000000" bg-color="#eeeeef" @change="sectionChange1($event,false)"></u-subsection>
								</view>
							</u-form-item>

						</u-form>
						<!-- 日历范围选择组件 -->
						<u-calendar
							v-model="show._add_time"
							mode="range"
							safe-area-inset-bottom
							btn-type="default"
							active-bg-color="#19be6b"
							range-bg-color="#dbf1e1"
							@change="calendarChange"
						></u-calendar>
						<!-- ****************** 自定义高级搜索表单结束 ****************** -->
					</view>
				</scroll-view>
				<view class="footer-btn">
					<view class="btn reset" @click="advancedSearchReset">重 置</view>
					<view class="btn confirm" @click="advancedSearchConfirm">确 定</view>
				</view>
			</view>
		</u-popup>
		<!-- 高级搜索弹窗结束 -->

		<!-- 页面内容结束 -->
		<!-- 全局公共浮球导航模块 -->
		<vk-data-float-ball :scroll-top="scrollTop"></vk-data-float-ball>
		<!-- #ifdef MP-WEIXIN -->
		<!-- 微信小程序专用隐私授权弹窗组件 -->
		<vk-mall-privacy-popup position="bottom"></vk-mall-privacy-popup>
		<!-- #endif -->
	</view>
</template>

<script>
var vk = uni.vk;			// vk依赖
var originalForms = {}; // 表单初始化数据
export default {
	data() {
		// 页面数据变量
		return {
			// 获取list数据的云函数请求路径
			url: "client/address.getList",
			// init请求返回的数据
			data: {
				list: [],
				total: "-",
				hasMore: true // 是否还有下一页数据
			},
			// 列表查询请求数据
			queryForm1: {
				// 分页数据
				pagination: {
					pageIndex: 1, //当前页码
					pageSize: 20 //每页显示数量
				},
				// 表单数据源
				formData: {
					_add_time: [],
					name: "",
					mobile: "",
					alias: ""
				},
				// 查询匹配规则
				columns: [
					{ key: "_add_time", mode: "[]" },
					{ key: "name", mode: "%%" },
					{ key: "mobile", mode: "%%" },
					{ key: "alias", mode: "=" }
				],
				// 排序规则
				sortRule: [
					{ name:"is_default", type:"desc" }, // desc降序 asc升序
					{ name:"_add_time", type:"desc" },
				]
			},
			// 列表搜索框 key 可以是 queryForm1.columns 中的任意1个key
			listSearch: { key: "name", placeholder: "输入姓名搜索" },
			// 页面状态
			state: {
				loadmore: "loading", // loadmore的显示状态
			},
			// 头部状态选择
			subsection1: {
				key: "alias", // 查询字段名
				current: 0, // 当前选中的索引
				list: [
					{ name: "全部", value: "" },
					{ name: "家", value: "家" },
					{ name: "公司", value: "公司" },
					{ name: "朋友", value: "朋友" },
					{ name: "客户", value: "客户" },
					{ name: "学校", value: "学校" },
					{ name: "其他", value: "其他" }
				]
			},
			// 每一项底部的拓展按钮
			footer: {
				actived: "",
				color: "#909399",
				list: [
					{
						text: "删除",
						click: (item, index) => {
							vk.confirm(`${item.name} ${item.mobile} ${item.formatted_address}`,"确定删除吗?","确定","取消",(res)=>{
								if(res.confirm){
									// 点击确定按钮后的回调
									vk.callFunction({
										url: 'client/address.delete',
										title:'请求中...',
										data:{
											_id: item._id
										},
										success:(data)=>{
											// 这里省去一次查询请求
											this.data.list.splice(index, 1);
										}
									});
								}
							});
						},
						showRule:(item)=>{
							return this.options.mode !== 'choose' ? true : false;
						}
					},
					{
						text: "编辑",
						click:(item)=> {
							this.pageToForm(item);
						}
					},
					{
						text: "复制",
						click: (item) => {
							let text = `${item.name} ${item.mobile} ${item.formatted_address}`;
							uni.setClipboardData({
								data: text,
								success: () => {
									vk.toast("内容已复制");
								}
							});
						},
						showRule:(item)=>{
							return this.options.mode !== 'choose' ? true : false;
						}
					},
					{
						text: "设为默认",
						main: true, // 颜色高亮显示
						click:(item) =>{
							vk.callFunction({
								url: 'client/address.setDefault',
								title:'请求中...',
								data:{
									_id: item._id
								},
								success:(data)=>{
									// 这里省去一次查询请求
									this.setDefault(item);
								}
							});
						},
						showRule:(item)=>{
							return this.options.mode !== 'choose' && !item.is_default ? true : false;
						}
					},
					{
						text: "选择TA",
						main: true, // 颜色高亮显示
						click:(item)=> {
							this.chooseAddress(item);
						},
						showRule:(item)=>{
							return this.options.mode === 'choose' ? true : false;
						}
					},
				]
			},
			// 页面上所有弹窗的开关
			show: {
				_add_time: false, // 高级搜索弹窗中的日历选择弹窗开关
				advancedSearch: false, // 高级搜索弹窗开关
			},
			loading: false, // 是否请求中
			scrollTop: 0, // 滚动条当前位置
			options:{
				mode:""
			}
		};
	},
	onPageScroll(e) {
		this.scrollTop = e.scrollTop;
	},
	// 监听 - 页面每次【加载时】执行(如：前进)
	onLoad(options = {}) {
		this.options = options;
		this.init(options);
	},
	// 监听 - 页面【首次渲染完成时】执行。注意如果渲染速度快，会在页面进入动画完成前触发
	onReady() {

	},
	// 监听 - 页面每次【显示时】执行(如：前进和返回) (页面每次出现在屏幕上都触发，包括从下级页面点返回露出当前页面)
	onShow() {},
	// 监听 - 页面每次【隐藏时】执行(如：返回)
	onHide() {},
	// 监听 - 页面下拉刷新
	onPullDownRefresh() {
		setTimeout(() => {
			uni.stopPullDownRefresh();
		}, 1000);
	},
	// 监听 - 页面触底部
	onReachBottom(options) {
		this.nextPage();
	},
	// 监听 - 点击右上角转发时 https://uniapp.dcloud.io/api/plugins/share.html#onshareappmessage
	onShareAppMessage(options) {

	},
	// 函数
	methods: {
		// 页面数据初始化函数
		init(options) {
			let that = this;
			console.log("init: ", options);
			// 拷贝一份表单的初始值
			originalForms["queryForm1"] = vk.pubfn.copyObject(that.queryForm1.formData);

			// 根据url参数alias，设置当前选中的状态
			if (options.alias) {
				let index = vk.pubfn.getListIndex(that.subsection1.list, "value", alias);
				that.sectionChange1(index, false);
			}

			// 查询
			that.search();
		},
		// 搜索查询
		search(e) {
			let that = this;
			that.queryForm1.pagination.pageIndex = 1;
			that.data.pageKey = true;
			that.getList();
		},
		// 加载下一页数据
		nextPage() {
			let that = this;
			if (that.state.loadmore == "loadmore") {
				that.state.loadmore = "loading";
				that.queryForm1.pagination.pageIndex++;
				that.getList();
			}
		},
		// 获取list数据
		getList(obj = {}) {
			let that = this;
			vk.pubfn.getListData2({
				that: that,
				url: that.url,
				success: obj.success
			});
		},
		// 顶部选项改变事件
		sectionChange1(index, search=true) {
			let that = this;
			if (index < 0) {
				return false;
			}
			that.subsection1.current = index;
			let key = that.subsection1.key;
			let value = that.subsection1.list[index].value;
			that.$set(that.queryForm1.formData, key, value);
			that.data.list = [];
			that.data.total = "-";
			// 搜索
			if (search) that.search();
		},
		// 高级搜索 - 确定按钮
		advancedSearchConfirm() {
			let that = this;
			that.show.advancedSearch = false;
			that.search();
		},
		// 高级搜索 - 重置按钮
		advancedSearchReset() {
			let that = this;
			that.queryForm1.formData = vk.pubfn.copyObject(originalForms["queryForm1"]);
			that.subsection1.current = 0;
			that.search();
		},
		// 折叠开关
		collapse(index, item) {
			let that = this;
			if (that.options.mode == 'choose') {
				that.chooseAddress(item);
			} else {
				that.footer.actived = that.footer.actived !== index ? index : "";
			}
		},
		chooseAddress(item){
			let that = this;
			const eventChannel = that.getOpenerEventChannel();
			if (eventChannel.emit) eventChannel.emit('choose', item);
			vk.navigateBack();
		},
		// 底部按钮显示判断
		footerShowFn(btn, item, index) {
			let that = this;
			if (typeof btn.showRule == "function") {
				return btn.showRule(item, index);
			} else {
				return true;
			}
		},
		// 折叠打开后的底部按钮点击事件
		footerBtn(item, index, btn) {
			let that = this;
			if (typeof btn.click === "function") {
				btn.click(item, index, btn);
			}
		},
		// 监听 - 日历组件的change事件
		calendarChange(e) {
			let that = this;
			that.$set(that.queryForm1.formData, "_add_time", [
				vk.pubfn.toTimeLong(e.startDate + " 00:00:00"),
				vk.pubfn.toTimeLong(e.endDate + " 23:59:59")
			]);
		},
		setDefault(item){
			let that = this;
			// 这里省去一次查询请求
			that.data.list.map((item, index) => {
				item.is_default = false;
			});
			item.is_default = true;
		},
		// 跳转到表单页面
		pageToForm(item){
			let that = this;
			let url = "./edit";
			if (item && item._id) url += `?_id=${item._id}`;
			vk.navigateTo({
				url,
				events: {
					// 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
					add: (data) => {
						// 当B页面运行 eventChannel.emit('add', { a:1 }); 时，会运行这里的代码逻辑。
						if (data.is_default) that.setDefault(data);
						that.data.list.unshift(data);
					},
					// 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
					update: (data) => {
						// 当B页面运行 eventChannel.emit('update', { a:1 }); 时，会运行这里的代码逻辑。
						if (data.is_default) that.setDefault(data);
						vk.pubfn.objectAssign(item, data);
					}
				},
				success: (res) => {
					// 通过eventChannel向被打开页面传送数据
					if (item) res.eventChannel.emit('data', item);
				}
			})
		},
		// 导入微信地址
		importWeixin(){
			let that = this;
			uni.chooseAddress({
				success(res) {
					that.pageToForm({
						name: res.userName,
						mobile: res.telNumber,
						position:{
							address: res.detailInfo,
							province: { code: "", name: res.provinceName },
							city: { code:"", name: res.cityName },
							area: { code:"", name: res.countyName },
						}
					});
				}
			})
		}
	},
	// 计算属性
	computed: {

	}
};
</script>
<style lang="scss" scoped>
.app{
	/* --main: #2b85e4;
	--secondary: rgba(76,128,96,0.2); */

	background-color: var(--bgcolor);
	min-height: calc(100vh - var(--window-top));
}

/* list主结构开始 */
.list-page {
	background-color: var(--bgcolor);

	/* 头部 */
	.list-head {
		.total-desc {
			font-size: 28rpx;
			color: #999;
			padding: 20rpx 30rpx 0rpx 30rpx;
			padding-bottom: 0;
			line-height: 52rpx;
			width: 100%;
		}

		.total-num {
			font-weight: bold;
			color: black;
			font-size: 26rpx;
			margin-left: 10rpx;
			margin-right: 10rpx;
		}

		.list-search {
			background-color: #ffffff;
			padding: 20rpx 30rpx;

			.subsection {
				margin-top: 20rpx;
			}

			.list-search-input {
				display: flex;

				.search-input {
					flex: 1;
				}

				.advanced-search {
					margin-left: 20rpx;
				}
			}
		}
	}

	.list-main {
		padding: 0rpx 0rpx 20rpx 0rpx;
	}

	.list-main:after{
		content:" ";
		display: block;
		height: 100rpx;
	}

	.list-footer{
		position: fixed;
		bottom: 0;
		left:0;
		width: 100%;
		height: 100rpx;
		z-index: 99;
		.btn-box{
			display: flex;
			width: 100%;
			height: 100%;
			align-items: center;
			>view{
				flex: 1;
				height: 100%;
				display: flex;
				justify-content: center;
				align-items: center;
			}
			.btn-secondary{
				background-color: #ffffff;
			}
			/* .btn-main{
				background-color: #ffffff;
				color: #000000;
			} */
			.btn-main{
				background-color: #19be6b;
				color: #ffffff;
			}
			.btn-one{
				margin: 0 10% 40rpx 10%;
				border-radius: 50rpx;
			}
		}
	}

}

/* list主结构结束 */

/* 高级搜索弹窗开始 */
.search-popup {
	background-color: #f3f3f3;

	.scroll-view {
		flex: 1;
		height: 1024rpx;
		padding: 0;
	}

	.footer-btn {
		display: flex;
		.btn {
			flex: 1;
			display: block;
			text-align: center;
			line-height: 80rpx;
		}
		.btn:active {
			opacity: 0.7;
		}
		.reset {
			color: #404040;
			background-color: #ffffff;
		}
		.confirm {
			background-color: #19be6b;
			color: #ffffff;
		}
	}

	::v-deep .u-form-item {
		background-color: #ffffff;
		display: block;
		padding: 20rpx;
		color: #7e7e7e;
		padding-top: 6rpx;
		color: #262626;
		margin-bottom: 20rpx;
	}

	.date-range {
		text-align: center;
		background-color: #f6f6f6;
		line-height: 60rpx;
		border-radius: 30rpx;
		color: #7f7f7f;
		width: 100%;
	}
}
/* 高级搜索弹窗结束 */

/* list-item开始 */
.list-item {
	margin: 20rpx;

	>.content {
		background-color: #ffffff;
		padding: 20rpx;
		color: #303133;

		.mt10{
			margin-top: 10rpx;
		}

		.text-one {
			display: -webkit-box;
			-webkit-box-orient: vertical;
			-webkit-line-clamp: 1;
			overflow: hidden;
		}

		.name{
			font-weight: bold;
			letter-spacing: 2rpx;
		}

		.mobile{
			margin-left: 20rpx;
			letter-spacing: 2rpx;
		}

		.tag{
			margin-left: 20rpx;
			position: relative;
			top: -4rpx;
			letter-spacing: 2rpx;
		}

		.address{
			margin-top: 20rpx;
		}
	}

	.collapse {
		display: none;
		padding: 20rpx;
		font-size: 24rpx;
		color: #909399;
		line-height: 40rpx;
		background-color: #ffffff;
		border-top: 1px solid #f8f8f8;

		grid-template-columns: repeat(5, 1fr);
		gap: 16rpx;
		box-sizing: border-box;
		direction: rtl; //反向填充

		>view {
			border: 2rpx solid #e4e7ed;
			border-radius: 20rpx;
			text-align: center;
			padding: 2rpx 10rpx;
			color: #909399;
		}
		>view.main {
			border: 2rpx solid #000000;
			color: #000000;
		}
	}

	.collapse.actived {
		display: grid;
	}
}
/* list-item结束 */

.choose-tips{
	color: #FA3534;
	padding: 10rpx 30rpx;
}

</style>
